package com.itheima.aspect;

import com.alibaba.fastjson.JSONObject;
import com.itheima.common.R;
import com.itheima.mapper.LogMapper;
import com.itheima.pojo.OperateLog;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Slf4j
@Aspect
public class CollectIonAspect {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private LogMapper logMapper;

    @Around ("@annotation(com.itheima.anno.Log)")
    public Object collectAspect(ProceedingJoinPoint joinPoint) throws Throwable {
        //请求url地址
        String url = request.getRequestURL().toString();
        //访问类名
        String targetClass = joinPoint.getTarget().getClass().getName();
        //目标方法名
        String targetMethod = joinPoint.getSignature().getName();
        //参数
        String methodParams = Arrays.toString(joinPoint.getArgs());

        long begin = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        long end = System.currentTimeMillis();
        //返回值(json格式)
        R string = (R) proceed;
        String methodReturn = JSONObject.toJSONString(string);
        //客户端浏览器信息
        String clientBrowser = request.getHeader("User-Agent");
        //客户端操作系统名
        String clientPlatform = request.getHeader("sec-ch-ua-platform");
        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //耗时时间
        long costTime = end - begin;

        OperateLog operateLog = new OperateLog(null, url, targetClass, targetMethod, methodParams, methodReturn, clientBrowser, clientPlatform, operateTime, costTime);
        //添加到数据库
        logMapper.insert(operateLog);
        log.info("参数{}", operateLog);
        return proceed;
    }
}
